package com.zyx.nettypro.bio;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zyx
 * @since 2021/9/18 17:48
 * desc: 基于BIO的服务案例
 */
public class BioServer {

    public static void main(String[] args) throws IOException {
        // 线程池机制

        // 思路
        // 1.创建一个线程池
        // 2.如果有客户端连接, 就创建一个线程, 与之通讯(单独写一个方法)
        @SuppressWarnings("AlibabaThreadPoolCreation")
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();

        // 创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动了");

        while (true) {
            System.out.println("主线程信息 id =" + Thread.currentThread().getId() +
                    " 名字=" + Thread.currentThread().getName());
            // 监听, 等待客户端连接
            System.out.println("等待连接......");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            // 创建一个线程, 与之通讯(单独写一个方法)
            newCachedThreadPool.execute(() -> {
                // 可以和客户端通讯
                handler(socket);
            });

        }
    }

    /**
     * 编写一个handler方法, 和客户端通信
     */
    public static void handler(Socket socket) {

        System.out.println("client连接成功, 线程信息 id =" + Thread.currentThread().getId() +
                " 名字=" + Thread.currentThread().getName());

        try {
            byte[] bytes = new byte[1024];
            // 通过socket获取输入流
            InputStream inputStream = socket.getInputStream();

            // 循环读取客户端发送的数据
            while (true) {

                System.out.println("client" + Thread.currentThread().getId() + "等待发送消息");

                int read = inputStream.read(bytes);
                if (read == -1) {
                    break;
                }
                // 输出客户端发送的数据
                System.out.println(new String(bytes, 0, read));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
